package com.example.yang.yixin.Activity;

import android.animation.ObjectAnimator;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.yang.yixin.Adapter.MusicGridAdapter;

import com.example.yang.yixin.R;
import com.example.yang.yixin.Service.WatchedService;
import com.example.yang.yixin.Utils.Class_info;
import com.example.yang.yixin.Utils.DimensionUtils;
import com.example.yang.yixin.Utils.ScreenLock;
import com.example.yang.yixin.Utils.SystemUtils;
import com.example.yang.yixin.Utils.T;
import com.example.yang.yixin.Views.RingProgress;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.nio.file.WatchService;
import java.util.ArrayList;
import java.util.List;

public class PhoneControlActivity extends BaseActivity{
    private Context mContext = PhoneControlActivity.this;//11
    private static final String ACTION_COUNT = "com.brilliantbear.putdownthephone.COUNT";
    private static final String ACTION_COUNT_MAX = "com.brilliantbear.putdownthephone.COUNT_MAX";
    private static final String ACTION_TIME_UP = "com.brilliantbear.putdownthephone.TIME_UP";
    private NavigationView mNavigationView;//11
    private DrawerLayout mDrawer;//11
    private FloatingActionButton fab;//11
    private RingProgress ringProgress;//11
    private CountReceiver receiver;//11
    private SharedPreferences sp;//11
    private ScreenLock screenLock;//11
    private ObjectAnimator downAnimation;//11
    private ObjectAnimator upAnimation;//11
    private SharedPreferences pref;
    List list = new ArrayList();
    private ImageView mIv_daohang;
    private ImageView mIv_meinfo;
    private    static boolean flag=false;
    private View view;



    @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_phone_control);
        initView();//初始化

        mIv_daohang=findViewById(R.id.iv_daohang);
        mIv_meinfo=findViewById(R.id.iv_meinfo);
        mIv_daohang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               mDrawer.openDrawer(Gravity.START);

            }
        });
        mIv_meinfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(PhoneControlActivity.this,MeActivity.class));
            }
        });
        initData();//加载数据
    }


    /*
    初始化
     */
    @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
    private void initData() {
        receiver = new CountReceiver();//广播接收器
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_COUNT);
        intentFilter.addAction(ACTION_COUNT_MAX);
        intentFilter.addAction(ACTION_TIME_UP);
        registerReceiver(receiver, intentFilter);//注册广播


        sp = getSharedPreferences("settings", MODE_PRIVATE);//作用不知道
        screenLock = new ScreenLock(this);//创建一把锁


        downAnimation = ObjectAnimator.ofFloat(fab, "translationY", 0, DimensionUtils.dp2px(getResources(), 120));
        downAnimation.setDuration(500);
        upAnimation = ObjectAnimator.ofFloat(fab, "translationY", DimensionUtils.dp2px(getResources(), 120), 0);
        upAnimation.setDuration(500);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pref = getSharedPreferences("user", MODE_PRIVATE);
                String identity = pref.getString("identity", "");
//设置只有模式二才进入
                if (checkMode(sp.getInt("mode", 0))) {
                    Intent intent = new Intent(PhoneControlActivity.this, WatchedService.class);
                    intent.putExtra("count", 100);
                    startService(intent);//后台服务
                    downAnimation.start();//倒计时
                }
                else{
                    if (identity.equals("老师")) {
                        if (!flag) {
                            if (Upsource()){
                                Snackbar.make(getWindow().getDecorView(),"控制请求已上传！（在您的班课界面上的学生手机会被控制）",Snackbar.LENGTH_SHORT).setAction("我知道了", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {


                                    }
                                }).show();

                            }
                            flag = true;

                        } else {
                            Setsource();
                            flag = false;
                        }
                    } else {
                        Snackbar.make(getWindow().getDecorView(),"抱歉你的权限不足！",Snackbar.LENGTH_SHORT).setAction("取消", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                            }
                        }).show();

                    }
                }

            }
        });

        /*
        设置侧滑菜单选项的监听器
         */

        mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.action_settings:
                        selectTime();
                        break;
                    case R.id.action_applock:
                        //模式选择
                        showModeDialog();
                        break;
                    case R.id.action_feedback:
                        showFeedbackDialog();
                        break;
                    case R.id.action_help:
                        showHelpDialog();
                        break;
                }
                mDrawer.closeDrawer(GravityCompat.START);//设置关闭的显示方式
                return true;
            }
        });

        if (sp.getBoolean("help", true)) {
            showHelpDialog();
        }

        ringProgress.setInnerText(countToTimeString(sp.getInt("time", 1) * 60));



    }

    private String[] timelist = { "1min", "2min", "3min", "4min", "5min", "6min", "7min", "8min", "9min", "10min",
            "11min", "12min", "13min", "14min", "15min", "16min", "17min", "18min", "19min", "20min",
            "21min", "22min", "23min", "24min", "25min", "26min", "27min", "28min", "29min", "30min",
            "31min", "32min", "33min", "34min", "35min", "36min", "37min", "38min", "39min", "40min",
            "41min", "42min", "43min", "44min", "45min", "46min", "47min", "48min", "49min", "50min",
            "51min", "52min", "53min", "54min", "55min", "56min", "57min", "58min", "59min", "60min",

    };

    private void selectTime() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("选择控制时间")
                .setIcon(R.mipmap.logo1)
                .setItems(timelist, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        dialog.dismiss();
                        settime(which);
                    }
                });
        builder.show();
    }
    private void settime(int time) {
        SharedPreferences.Editor edit = sp.edit();
        edit.putInt("time", time+1 ).apply();
    }

    private String[] modeList = {"教师控制模式", "学生自用模式"};

    private void showModeDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("选择模式")
                .setIcon(R.mipmap.logo1)
                .setItems(modeList, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        dialog.dismiss();
                        setMode(which);
                    }
                });
        builder.show();
    }

    private void setMode(int mode) {
        SharedPreferences.Editor edit = sp.edit();
        if (mode == 0) {
            if (!screenLock.isActive()) {
                screenLock.activeAdmin();
            }
            edit.putInt("mode",0).apply();
        } else if (mode == 1) {
            edit.putInt("mode",1).apply();
        }
    }

    private void Setsource() {
        pref = getSharedPreferences("user", MODE_PRIVATE);

        String bkpassword = pref.getString("bkpassword", "");
        String phonecontrol="0";
        String jsonurl = "http://47.106.141.161/MyFirstAndroidApp/ControlServlet?bkpassword="+ bkpassword+"&control="+phonecontrol;
        RequestQueue mQueue = Volley.newRequestQueue(this);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(jsonurl, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {

                    boolean ss=response.getBoolean("tf");



                } catch (JSONException e) {

                    Log.e("json错误", e.getMessage());
                }
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.e("TAG错误", volleyError.getMessage(), volleyError);
                    }
                }) {
            protected Response<JSONObject> paraeNetworkResponse(NetworkResponse response) {
                try {
                    JSONObject jsonObject = new JSONObject(new String(response.data, "utf-8"));
                    return Response.success(jsonObject, HttpHeaderParser.parseCacheHeaders(response));
                } catch (JSONException je) {
                    return Response.error(new ParseError(je));
                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                }

            }
        };


        mQueue.add(jsonObjectRequest);


    }

    private Boolean Upsource() {
        pref = getSharedPreferences("user", MODE_PRIVATE);

        String bkpassword = pref.getString("bkpassword", "");
        String phonecontrol="1";
        String jsonurl = "http://47.106.141.161/MyFirstAndroidApp/ControlServlet?bkpassword="+ bkpassword+"&control="+phonecontrol;
        RequestQueue mQueue = Volley.newRequestQueue(this);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(jsonurl, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {

                    boolean ss=response.getBoolean("tf");



                } catch (JSONException e) {

                    Log.e("json错误", e.getMessage());
                }
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.e("TAG错误", volleyError.getMessage(), volleyError);
                    }
                }) {
            protected Response<JSONObject> paraeNetworkResponse(NetworkResponse response) {
                try {
                    JSONObject jsonObject = new JSONObject(new String(response.data, "utf-8"));
                    return Response.success(jsonObject, HttpHeaderParser.parseCacheHeaders(response));
                } catch (JSONException je) {
                    return Response.error(new ParseError(je));
                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                }

            }
        };


        mQueue.add(jsonObjectRequest);
       return true;

    }


    /*
    一打开该功能的提示，可不做
     */
    private void showFeedbackDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("友课")
                .setIcon(R.mipmap.logo1)
                .setMessage(R.string.feedback)
                .setPositiveButton("复制邮箱账号", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        ClipboardManager clipboardManager = (ClipboardManager) mContext.getSystemService
                                (CLIPBOARD_SERVICE);
                        clipboardManager.setText("2460228341@qq.com");
                        T.showSingle(mContext, "复制成功");
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        builder.show();
    }
    private void showHelpDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("帮助")
                .setMessage(Html.fromHtml(this.getString(R.string.help)))
                .setPositiveButton("知道了", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setNegativeButton("不再提示", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        sp.edit().putBoolean("help", false).apply();
                    }
                });
        builder.show();
    }



    /*
    反馈的信息，可不做
     */


    /*
    增加判断处理检测使用何种模式
     */
    private boolean checkMode(int mode) {
        boolean result = false;
        if(mode == 1){
            if (screenLock.isActive()) {
                screenLock.lock();
                result = true;
            } else {
                showActiveDialog();
            }
        }
        return result;
    }

    private void showActiveDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setIcon(R.mipmap.logo1)
                .setTitle(R.string.app_name)
                .setMessage(R.string.active_message)
                .setPositiveButton("去激活", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();//隐藏对话框
                        screenLock.activeAdmin();//获取权限
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        builder.show();
    }

    /*
    初始化
     */
    private void initView() {
        fab = (FloatingActionButton) findViewById(R.id.fab);//悬浮按钮暂停键
        mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);//创建侧滑菜单
        mNavigationView = (NavigationView) findViewById(R.id.navigation_view);//指定侧滑菜单的子选项
     //mToolbar导航栏的按钮
       /* ActionBarDrawerToggle mToggle = new ActionBarDrawerToggle(this, mDrawer, mToolbar, R.string
                .drawer_open, R.string.drawer_close);

        mToggle.syncState();
        mDrawer.setDrawerListener(mToggle);*/
        ringProgress = (RingProgress) findViewById(R.id.ring_progress);
    }


    //注销广播
    protected void onDestroy() {
        super.onDestroy();

        unregisterReceiver(receiver);
    }



    //注册广播
    public class CountReceiver extends BroadcastReceiver {

        @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ACTION_COUNT)) {
                int count = intent.getIntExtra("count", 0);
                setRingProgress(count);
            } else if (intent.getAction().equals(ACTION_COUNT_MAX)) {
                int max = intent.getIntExtra("count_max", 100);
                ringProgress.setMax(max);
            } else if (intent.getAction().equals(ACTION_TIME_UP)) {
                upAnimation.start();
            }

        }
    }



    /*
    设置倒计时显示的样式
     */
    private String countToTimeString(int count) {
        int minute = count / 60;
        int second = count % 60;

        StringBuilder sb = new StringBuilder();
        if (minute > 9) {
            sb.append(minute);
        } else {
            sb.append("0").append(minute);
        }

        sb.append(":");

        if (second > 9) {
            sb.append(second);
        } else {
            sb.append("0").append(second);
        }
        return sb.toString();
    }
/*
设置计时器的计时显示
 */
    private void setRingProgress(int count) {
        ringProgress.setProgress(count);
        ringProgress.setInnerText(countToTimeString(count));
    }


/*
设置返回键的功能失效
 */
    public void onBackPressed() {
        if (SystemUtils.isServiceRunning(this, "com.brilliantbear.putdownthephone.service.WatchedService")) {
            Intent home = new Intent(Intent.ACTION_MAIN);
            home.addCategory(Intent.CATEGORY_HOME);
            startActivity(home);
        } else {
            super.onBackPressed();
        }
    }
}
